package com.spring.controller;

import com.spring.dao.UserDao;
import com.spring.pojo.JsonResult;
import com.spring.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
public class LoginController {

    @Autowired
    private UserDao userDao;

    /**用户注册
     * @PostMapping描述方法时，表示此方法只能处理post请求
     * @RequestBody描述方法参数，表示将请求中的json串转换为对象赋值给参数
     * */
    @PostMapping("/register")
    public JsonResult doCreate(@RequestBody User user){
        user.setCreatedTime(new Date());
        user.setModifiedTime(new Date());
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userDao.insert(user);
        return new JsonResult("register ok");
    }

    /**用户登陆
     * @PathVariable注解描述方法参数时，表示参数的值来自请求url中{var}变量的值
     * */
    @PostMapping("/login/{username}/{password}")
    public JsonResult doLogin(@PathVariable("username") String username,
                              @PathVariable("password") String password,
                              HttpSession session){
        User user = userDao.selectByUsername(username);
        if(user==null)
            throw new RuntimeException("用户不存在");
        if(!user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes())))
            throw new RuntimeException("密码不正确");
        session.setAttribute("user", user);
        return new JsonResult("login ok");
    }

}
